package controller

import (
	"example.com/m/DATABASE"
	"example.com/m/common"
	"example.com/m/model"
	"example.com/m/response"
	"example.com/m/util"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
)

func Restgiter(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	name := ctx.PostForm("name")
	phone := ctx.PostForm("phone")
	password := ctx.PostForm("password")

	//数据验证
	if len(phone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须是11位")
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	//如果名称没有传，给一个10位字符串
	if len(name) == 0 {
		name = util.RandomString(10)
	}
	log.Println(name, phone, password)

	//判断手机号是否存在
	if isPhoneExist(DB, phone) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户已存在")
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "用户已存在",
		})
		return
	}
	//创建用户
	//加密存储
	Hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "加密错误")
	}
	newUser := model.User{
		Model:   gorm.Model{},
		Name:    name,
		Phone:   phone,
		Pasword: string(Hashed),
	}
	DB.Create(&newUser)
	//返回结果
	response.Success(ctx, nil, "注册成功")

}

func Login(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	phone := ctx.PostForm("phone")
	password := ctx.PostForm("password")
	//数据验证
	if len(phone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须是11位")
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	//判断手机号是否存在
	var user model.User
	DB.Where("phone = ?", phone).Find(&user)
	if user.ID == 0 {
		//等于0表示用户不存在
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")

	}
	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Pasword), []byte(password)); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg": "密码错误",
		})
		return
	}

	//密码验证通过，发放token给前端
	token, err := common.ReleaseToken(user)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "系统异常",
		})
		log.Println("token generate error: %v", err)
	}

	//返回结果
	ctx.JSON(200, gin.H{
		"code": 200,
		"data": gin.H{"token": token},
		"msg":  "登录成功",
	})
	response.Success(ctx, gin.H{"token": token}, "登录成功")
}

func Info(ctx *gin.Context) {
	//获取用户个人信息，
	user, _ := ctx.Get("user")
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{"user": DATABASE.ToUserDto(user.(model.User))},
	})

}
func isPhoneExist(db *gorm.DB, phone string) bool {
	var user model.User
	db.Where("phone = ?", phone).Find(&user)
	if user.ID != 0 {
		return true
	}
	return false
}
